# -*- coding: utf-8 -*-
from django.http import HttpResponse
from news.models import News
from projects.models import Project 

from pygameweb.notification.models import Subscription, CHOICES as choices
from pygameweb.notification.templatetags.subscription_tags import subscription_link

class SubscriptionHandler(object):

    def process_view(self, request, view_func, view_args, view_kwargs):
        def ajax_wrapper(msg, new_link=""):
            if request.is_ajax():
                return HttpResponse("%s\n%s" % (msg, new_link))
            else:
                request.user.message_set.create(message=msg)
                return
        if request.method == "GET" and ("subscribe" in request.GET or
          "unsubscribe" in request.GET):
          if not request.user.is_authenticated():
              # tell that he have to log in to subscribe
              return ajax_wrapper("please log in to subscribe")
          elif "subscribe" in request.GET:
              action = "sub"
              obj = request.GET["subscribe"]
          else:
              action = "unsub"
              obj = request.GET["unsubscribe"]
          
          obj_describtion = obj = obj.replace("-", " ")
          if obj not in choices.keys():
              return ajax_wrapper("Invalid parameters to %s %s" % (
                                        action+"scribe", obj))
          kind = choices[obj]
          path = request.path.lstrip("/")
          if "/" in path:
              urlpart, rest = path.split("/", 1)
          else:
              urlpart, rest = path, ""
          obj_id = request.GET.get("id", None)
          add_id_to_url = bool(obj_id)
          cls = None
          if  kind == "nc" and urlpart == "news":
              cls = News
          elif kind in ("pc", "pr") and urlpart == "projects":
              cls = Project

          if cls and not obj_id:
              try:
                  slug = view_kwargs.get("slug", view_kwargs.get("project_slug", None))
                  if slug:
                      obj_id = cls.objects.get(slug=slug).id
              except News.DoesNotExist:
                  pass
          obj, created = Subscription.objects.get_or_create(user=request.user, 
                                                kind=kind, object_id=obj_id)
          if action == "sub":
              if created:
                  obj.save()
                  msg = "Successfully subscribed to %s" % obj_describtion
              else:
                  msg = "You already subscribed to %s" % obj_describtion
          else:
              if created:
                  msg = "You have not subscribed to %s" % obj_describtion
              else:
                  obj.delete()
                  msg = ("Successfully removed your subscription to %s" % 
                                                          obj_describtion)
                                                          
          return ajax_wrapper(msg, subscription_link(request, kind, obj_id, add_id_to_url))
          
          
    def process_response(self, request, response):
        if response.status_code == 404:
            return self.process_view(request, None, [], {}) or response
        return response